﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net;
using DataObjects;
using Newtonsoft.Json;

namespace GT5RemoteMobile
{
    public partial class NewRace : System.Web.UI.Page
    {
        protected List<TrackData> tracks;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                tracks = new List<TrackData>();

                bool success = false;
                int retryCount = 5;

                while (!success)
                {
                    try
                    {
                        if (retryCount == 0)
                            break;
                        GetTracks();
                        success = true;
                    }
                    catch (Exception)
                    {
                        success = false;
                        retryCount--;
                    }
                }
                if (!success)
                    Response.Redirect("default.aspx");
            }

            //HttpWebRequest trackDataRequest = WebRequest.Create(new Uri(Resources.Settings.appUrl + "Data/TrackData.js")) as HttpWebRequest;
            //using (HttpWebResponse response = trackDataRequest.GetResponse() as HttpWebResponse)
            //{
            //    StreamReader reader = new StreamReader(response.GetResponseStream());
            //    string jsonData = reader.ReadToEnd();
            //    tracks = JsonConvert.DeserializeObject<List<TrackData>>(jsonData);
            //}
        }

        private void GetTracks()
        {
            HttpWebRequest trackDataRequest = WebRequest.Create(new Uri("https://us.gran-turismo.com/us/gt5/user/" + Session["psnid"] + "/remoterace/")) as HttpWebRequest;
            trackDataRequest.Method = "GET";
            trackDataRequest.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
            trackDataRequest.Referer = "https://us.gran-turismo.com/us/gt5/user/" + Session["psnid"];
            trackDataRequest.Headers.Add("Cookie", Session["jsessionid"].ToString());

            using (HttpWebResponse response = trackDataRequest.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string s;
                bool reachedCode = false;
                TrackData track = new TrackData();
                while (!reader.EndOfStream)
                    s = ParseTrackData(reader, ref reachedCode, ref track);
                if (tracks.Count == 0)
                {
                    Context.Response.Redirect("RaceStatus.aspx");
                }
            }
        }

        private string ParseTrackData(StreamReader reader, ref bool reachedCode, ref TrackData track)
        {
            string s;
            s = reader.ReadLine();
            if (!reachedCode)
            {
                if (s.Contains("\"remote_event_list\""))
                {
                    reachedCode = true;
                }
            }
            else
            {
                if (s.Contains("course_logo"))
                {
                    // parse logo path
                    track.CourseLogoUrl = s.Split('"')[3];
                }
                if (s.Contains("race_info_minute"))
                {
                    // parse race time
                    string raceTime = s.Split('"')[3];
                    int length = raceTime.LastIndexOf('.') - (raceTime.LastIndexOf('/') + 1);
                    track.RaceTime = raceTime.Substring(
                            raceTime.LastIndexOf('/') + 1, length
                        );
                }
                if (s.Contains("entry_max"))
                {
                    // parse number of racers
                    string numOfDrivers = s.Split('"')[6];
                    int length = numOfDrivers.LastIndexOf('<') - (numOfDrivers.LastIndexOf("/>") + 2);
                    track.MaxDrivers = int.Parse(
                        numOfDrivers.Substring(
                            numOfDrivers.LastIndexOf("/>") + 2, length
                        )
                    );
                }
                if (s.Contains("lap"))
                {
                    // parse number of laps
                    string lapInfo = s.Substring(
                        s.LastIndexOf("</span>"),
                        s.LastIndexOf("</dd") - s.LastIndexOf("</span>"));
                    track.LapCount = lapInfo.Substring(7, lapInfo.LastIndexOf('(') - 7);
                    track.RaceTime = lapInfo.Substring(lapInfo.LastIndexOf("t ") + 1,
                        3);
                }
                if (s.Contains("/car/thumbnail"))
                {
                    // parse car image
                    track.CarImageUrl = s.Split('"')[1];
                }
                if (s.Contains("gt5bspec.selectEvent"))
                {
                    // parse course number and name, add to collection, create new object
                    track.TrackID = int.Parse(s.Substring(s.LastIndexOf('(') + 1, 4));
                    string title = s.Split(')')[2];
                    title = title.Split('"')[2];
                    track.TrackName = title.Split('/')[1];
                    track.FeaturedCar = title.Split('/')[0];
                    tracks.Add(track);
                    track = new TrackData();
                }
            }
            return s;
        }

        protected void SelectTrack(object sender, EventArgs e)
        {
            Console.Write(sender.ToString());
        }

    }
}